import React, { useState, useRef, useEffect } from 'react'
import { message, Spin, Button, Modal, notification } from 'antd'
import { ExclamationCircleOutlined, ExportOutlined } from '@ant-design/icons'

import { FCQueryPage } from '@components'
import { useMainContext } from '@contexts/MainContext'
import { formFields, tableColumns, Detail } from './userauthconfig'

import { useActivate, useUnactivate } from 'react-activation'

import {
  queryUserInfo,
  saveOrUpdateUserRole,
  exportUserInfo,
  queryCfgProUnits
} from '@apis/userApi'
import { querySecRoleMenuInfo } from '@apis/roleApi'

import styles from './styles/userConfig.module.css'

const querySecRoleMenuInfoParams = {
  currentPage: 1,
  pageSize: 50,
  queryDto: {}
}

const { confirm } = Modal

const UserConfig = ({hiddden=false}) => {
  const { isButtomShow } = useMainContext()

  const [loading, setLoading] = useState(false)
  //分页ref
  const pageRef = useRef()

  //子页面ref
  const detailRef = useRef()

  //表格字段
  const columns = tableColumns()

  //新增弹窗状态标记
  const [visible, setVisible] = useState(false)

  //已选择用户数据
  const [userRoleInfo, setUserRoleInfo] = useState({})

  //编辑弹窗
  const handleClickAddButton = (record) => {
    if (record.userCode) {
      setUserRoleInfo(record)
      // console.log(record.userRoleList)
      setVisible(true)
    }
  }

  //新增弹窗 --> 保存
  const onOk = (data) => {
    setLoading(true)
    let obj = {}
    let userList = []
    data.dataList?.forEach((item) => {
      let obj2 = {}
      obj2.roleId = item.roleId
      obj2.authUnitCodeList = item.authUnitCodeList
      userList.push(obj2)
    })
    obj.userCode = data.userCode
    obj.userRoleList = userList
    // console.log('obj===>',obj);
    // return
    //新增角色权限
    saveOrUpdateUserRole({
      params: obj,
      success: () => {
        setLoading(false)
        // message.success('操作成功')
        pageRef.current.reQuery()
        setVisible(false)
      },
      failure: () => {
        setLoading(false)
      }
    })
  }

  //新增弹窗 --> 取消
  const onCancel = () => {
    if (loading) return
    //子页面暴露给主页面的方法 用于重新渲染子页面表格
    // detailRef.current.setDataList(userRoleInfo.userRoleList)
    setVisible(false)
  }

  const onBeforeQuery = () => {
    // console.log('onBeforeQuery')
  }

  /** 定义表格属性 */
  const tableProps = {
    columns: [...columns],
    rowKey: 'userCode',
    actionColumn: isButtomShow('630103') ? {
      // 定制操作栏的内容
      title: '操作',
      width: 150,
      elements: [
        {
          type: 'button',
          icon: 'EditOutlined',
          text: '编辑',
          onClick: handleClickAddButton,
        },
      ],
    } : null,
  }

  // 角色集合
  const [roleDataList, setRoleDataList] = useState([])

  const exportList = () => {
    confirm({
      title: '是否导出?',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        const data = pageRef.current.getParams() //获取表单数据
        exportUserInfo({
          params: data,
          success: (res) => {
            message.success(`导出成功,稍后请前往数据管理下载`)
          },
          failure: (res) => {
            notification.warning({
              message: res.message,
              description: res.description || '',
            })
          },
        })
      },
    })
  }

  /** 定义查询面板表单的属性 */
  const searchFormProps = {
    layoutProps: {
      layout: 'grid',
      gridConfig: { colCount: 3 },
    },
    submitButton: {
      show: true,
      label: '查询',
      icon: 'SearchOutlined',
    },
    resetButton: {
      show: true,
      label: '重置',
      icon: 'UndoOutlined',
    },
    fields: [...formFields(roleDataList, hiddden)],
    initialValues: {},
    // extraTail: (
    //   <>
    //     {isButtomShow('070101') && !hiddden ? (
    //       <Button onClick={exportList} icon={<ExportOutlined />}>
    //         清单导出
    //       </Button>
    //     ) : null}
    //   </>
    // )
  }

  /** 定义分页器属性 */
  const paginationProps = {
    pageSize: 20,
    showSizeChanger: true,
    showTotal: true,
  }

  /** 定义接口属性 */
  const apiConfigs = { query: queryUserInfo }

  const initData = async () => {
    // setLoading(true)

    //角色
    const {data: roleData, error: roleError} = await querySecRoleMenuInfo(querySecRoleMenuInfoParams)
    // 获取机构树
    const {data: unitTreeData, error: unitTreeError} = await queryCfgProUnits()
    // setLoading(false)
  
    if(roleError) return
    setRoleDataList(roleData.pageList)

    if(unitTreeError) return
    // detailRef?.current?.setUnitData(unitTreeData) 树
    const newUnitList = unitTreeData.map((item) => ({
      value: item.unitCode,
      label: item.unitName,
    }))
    detailRef?.current?.setUnitData(newUnitList)

  }

  useEffect(() => {
    initData()
  }, [])

  useActivate(() => {
    initData()
  })

  return (
    <div className={`page-content ${styles.userConfig}`}>
      <div className="table-spin-container" style={{ display: loading ? '' : 'none' }}>
        <Spin size="large" spinning={loading} />
      </div>
      {/* <Spin spinning={loading}> */}
      <FCQueryPage
        tableProps={tableProps}
        searchFormProps={searchFormProps}
        paginationProps={paginationProps}
        apiConfigs={apiConfigs}
        onBeforeQuery={onBeforeQuery}
        pageRef={pageRef}
      />
      {/* </Spin> */}
      <Detail
        userRoleInfo={userRoleInfo}
        roleDataList={roleDataList}
        visible={visible}
        onOk={onOk}
        onCancel={onCancel}
        detailRef={detailRef}
      />
    </div>
  )
};

export default UserConfig;
